/**
 * 
 */
package com.ideeli.webextractor.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Scanner;

import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.apache.log4j.xml.DOMConfigurator;

import com.ideeli.webextractor.domain.ProductDetail;
import com.ideeli.webextractor.domain.SkuVpn;

/**
 * @author sa
 * 
 */
public class Utility
{
	private static final Logger logger = Logger.getLogger(Utility.class);

	public static void saveImage(String imageUrl, String destinationFile) throws IOException
	{
		File f= new File(destinationFile);
		
		URL url = new URL(imageUrl);
		InputStream is = url.openStream();
		OutputStream os = new FileOutputStream(f);

		byte[] b = new byte[2048];
		int length;

		while ((length = is.read(b)) != -1)
		{
			os.write(b, 0, length);
		}

		is.close();
		os.close();
	}

	// infoCodesWE : VPN: SSG-550M-SH | SKU: 1010551 | Warranty Information
	public static void parseInfoCodesWE(String str, ProductDetail prodDetail)
	{

		logger.debug("Extract SKU from the product:");
		logger.debug(str);

		Scanner scn = new Scanner(str);

		scn.useDelimiter(" ");
		String skuno = "";
		String vpnNo = "";
		while (scn.hasNext())
		{
			String token = scn.next();
			// System.out.println("token="+token);
			if ("SKU:".equals(token))
			{
				skuno = scn.next();
				continue;
			}
			if ("VPN:".equals(token))
			{
				vpnNo = scn.next();
				continue;
			}
		}

		logger.info("skuno=" + skuno);
		logger.info("vpnNo=" + vpnNo);

		prodDetail.setSku(skuno.trim());
		prodDetail.setVpn(vpnNo.trim());

	}

	//if changes made here then also make changes in parseInfoCodesWE
	public static SkuVpn extractSKU(String str)
	{

		logger.debug("Extract SKU from the product:");
		logger.debug(str);

		str = str.replaceAll("\\n", " ");
		Scanner scn = new Scanner(str);

		scn.useDelimiter(" ");
		String skuno = "";
		String vpnNo = "";
		while (scn.hasNext())
		{
			String token = scn.next();
			logger.debug("token=" + token);
			if ("SKU:".equals(token))
			{
				skuno = scn.next();
//				skuno=skuno.replaceAll("#", "");
				continue;
			}
			if ("VPN:".equals(token))
			{
				vpnNo = scn.next();
//				vpnNo=vpnNo.replaceAll("#", "");
				continue;
			}
		}
		
		SkuVpn skuVpn= new SkuVpn();
		skuVpn.setSku(skuno);
		skuVpn.setVpn(vpnNo);

		logger.debug("skuno=" + skuno);
		logger.debug("vpnNo=" + vpnNo);
		// skus.add(skuno);
		return skuVpn;

	}

	// Category:-Network-Devices\nSubCategory: Routers & Components\nProduct
	// Type: Router Components
	public static void parseCategory(String str, ProductDetail prodDetail)
	{
		Scanner scn = new Scanner(str);
		scn.useDelimiter("\\n");

		while (scn.hasNext())
		{
			String token = scn.next();
			Scanner scn2 = new Scanner(token);
			scn2.useDelimiter(": ");

			String token2 = scn2.next().trim();
			String value = scn2.next().trim();

			System.out.println("tokne2=" + token2 + " value=" + value);
			if ("Category".equals(token2.trim()))
			{
				prodDetail.setCategory(value);

			}
			else if ("Sub Category".equals(token2.trim()))
			{
				prodDetail.setSubCategory(value);

			}
			else if ("Product Type".equals(token2.trim()))
			{
				prodDetail.setProductType(value);

			}

		}

	}

	// $ 9,095.41 EXCL GST
	public static String extractPrice(String price)
	{
		price = price.replaceAll("\\$", "");
		price = price.replaceAll("EXCL", "");
		price = price.replaceAll(",", "");
		price = price.replaceAll("GST", "").trim();

		logger.warn("yourPrice:" + price);
		return price;

	}

	public static void parseBasicProdInformation(String prodInfo, ProductDetail detail)
	{
		Scanner scn = new Scanner(prodInfo);
		scn.useDelimiter("\\n");
		Map<String, String> basicInfo = new HashMap<String, String>();

		while (scn.hasNext())
		{
			String token = scn.next().trim();
			Scanner scn2 = new Scanner(token);
			scn2.useDelimiter(": ");

			String token2 = scn2.next().trim();
			String value = scn2.next().trim();
			basicInfo.put(token2, value);
		}

		detail.setBaseProps(basicInfo);

	}

	public static void parseExtendedProdInformation(String prodInfo, ProductDetail detail)
	{
		Scanner scn = new Scanner(prodInfo);
		scn.useDelimiter("\\n");
		// Map<String, Map<String, String>> extendedInfo = new HashMap<String,
		// Map<String, String>>();
		Map<String, String> extInfo = new LinkedHashMap<String, String>();
		// Map<String, List<String>> extInfoMval = new HashMap<String,
		// List<String>>();
		List<String> listExt = new ArrayList<String>();

		while (scn.hasNext())
		{
			String token = scn.next().trim();
			if (isExceptionList(token))
				continue;

			if (token.contains(":"))
			{
				Scanner scn2 = new Scanner(token);
				scn2.useDelimiter(":");
				try
				{
					String token2 = scn2.next().trim();
					logger.debug("token2==" + token2);
					String value = scn2.next().trim();

					if (!extInfo.containsValue(value))
					{
						if (extInfo.containsKey(token2))
						{
							String newVal = extInfo.get(token2) + ", " + value;
							extInfo.put(token2, newVal);
						}
						else
						{
							extInfo.put(token2, value);
						}
					}
					else
					{
						extInfo.put(token2, value);
					}

				}
				catch (NoSuchElementException e)
				{
					token = token.replaceAll(":", "");

					if (!listExt.contains(token))
					{
						listExt.add(token);
					}

				}
			}
			else
			{
				token = token.replaceAll(":", "");

				if (!listExt.contains(token))
				{
					listExt.add(token);
				}
			}
		}

		detail.setExtPropMap(extInfo);
		detail.setExtPropList(listExt);
	}

	public static void printMap(Map<String, String> map)
	{
		for (String key : map.keySet())
		{
			logger.debug("" + key + " : " + map.get(key));

			// System.out.println("key:" + key);
			// System.out.println("value:" + map.get(key));

			// System.out.println("");
		}
	}

	public static String readFile(String fileName)
	{
		StringBuilder fileContent = new StringBuilder();
		try
		{
			FileReader input = new FileReader(fileName);
			BufferedReader bufRead = new BufferedReader(input);

			String line; // String that holds current file line
			int count = 0; // Line number of count
			line = bufRead.readLine();
			count++;

			while (line != null)
			{
				// System.out.println(count + ": " + line);
				fileContent.append(line);
				fileContent.append("\n");
				line = bufRead.readLine();

				count++;
			}

			bufRead.close();

		}
		catch (ArrayIndexOutOfBoundsException e)
		{
			logger.error("Usage: java ReadFile filename\n");
		}
		catch (IOException e)
		{
			logger.error(e);
		}

		return fileContent.toString();

	}

	private static boolean isExceptionList(String str)
	{
		List<String> exceptionList = new ArrayList<String>();

		exceptionList.add("Alarm");
		exceptionList.add("Battery Information");
		exceptionList.add("General Information");
		exceptionList.add("Media & Performance");
		exceptionList.add("Miscellaneous");
		exceptionList.add("Additional Information:");

		exceptionList.add("Technical Information");
		exceptionList.add("Interfaces/Ports");
		exceptionList.add("Physical Characteristics");
		exceptionList.add("Product Information");
		exceptionList.add("Power Description");
		exceptionList.add("Warranty");
		exceptionList.add("Wireless Specifications");
		exceptionList.add("I/O Expansions");
		exceptionList.add("Storage");
		exceptionList.add("Memory");
		exceptionList.add("Network & Communication");
		exceptionList.add("Software");
		exceptionList.add("System Specification");

		exceptionList.add("Management & Protocols");
		exceptionList.add("Manageable");
		exceptionList.add("Manufacturer Website Address");

		return exceptionList.contains(str);
	}

	public static boolean isNull(String str)
	{
		if (str == null)
			return true;

		if (str.trim().equals(""))
			return true;

		return false;

	}

	public static float round2(float value)
	{
		float result = value * 100;
		result = Math.round(result);
		result = result / 100;
		return result;
	}

	public static Date getCurrentTS()
	{
		long timeNow = Calendar.getInstance().getTimeInMillis();
		Timestamp ts = new Timestamp(timeNow);

		return ts;

	}
	/*
	 * <table> -- <table align="left" class="attribute">
	 * <td -- <td style="text-align: left; "
	 */
	public static String formatExtendedHtml(String innerHtml)
	{
		innerHtml = innerHtml.replaceAll("<table>", "<table align=\"left\" class=\"attribute\">");
		innerHtml = innerHtml.replaceAll("<td", "<td style=\"text-align: left; \"");

		return innerHtml;

	}
	
	
	public static String getProductName(String productName) {
		
		
		if(productName!=null && productName.length()>91)
			return (productName.substring(0, 91));
		
		if(productName!=null && productName.length()<91)
		{
			StringBuilder tmp=new StringBuilder();
			for(int j=90;j>productName.length();j--)
				tmp.append(" ");
			tmp.append(".");
			
			return productName+tmp.toString();
		}
			
		return productName;
	}
	
	public static void initlog4j()
	{
		DOMConfigurator.configure("log4jconfig.xml");
		MDC.put("USERID", System.getProperty("user.name"));
		logger.debug("log4j configured.");
	}

}
